<template lang="">
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb  separator="/">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图 -->
<!-- shadow="hover" :鼠标悬浮时显示阴影 -->
<el-card class="box-card" shadow="hover">
  <!-- 栅格 
  Row 组件提供 gutter 属性来指定每一栏之间的间隔，默认间隔为 0。-->
  <el-row :gutter="20">
  <el-col :span="10">
    <!-- 执行查询操作 -->
<el-input placeholder="请输入需要查询的用户信息..."
          clearable
            v-model="queryTxt"
            @clear="getUserList"
            @keyup.native.13="getUserList">        
<!--   @keyup.13 正常调用无效  添加上native覆盖element自己封装的@keyup事件 -->
  <!-- slot="append" :可通过 slot 来指定在 input 中前置(slot="prepend")或者后置内容。 -->
    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
  </el-input>
  </el-col>
   <!-- <el-button type="primary">添加</el-button> -->
   <el-button @click="addDrawer = true" type="primary" style="margin-left: 16px;">
  添加
</el-button>
  <!-- <el-col :span="8">
  </el-col> -->
</el-row>
<!-- 用户表格展示区域 -->
<el-row>
    <el-table
    :data="userList"
    style="width: 100%"
    stripe border show-header highlight-current-row
   >
   <el-table-column
      type="index"
      label="#"
      width="180">
    </el-table-column>
    <el-table-column
      prop="username"
      label="用户名"
      width="180">
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱"
      width="180">
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="电话">
    </el-table-column>
    <el-table-column
      label="操作">
      <template slot-scope="scope">
        <!-- 提示文字 -->
        <el-tooltip class="item" effect="dark" content="修改用户" :enterable="false" placement="right-start">
       <el-button type="primary" icon="el-icon-edit" circle @click="showEditDrawer(scope.row)"></el-button>
    </el-tooltip>
     <el-tooltip class="item" effect="dark" content="检查用户" :enterable="false"  placement="right-start">
       <el-button type="success" icon="el-icon-check" circle></el-button>
    </el-tooltip>
     <el-tooltip class="item" effect="dark" content="用户消息" :enterable="false" placement="right-start">
        <el-button type="info" icon="el-icon-message" circle></el-button>
    </el-tooltip>
     <el-tooltip class="item" effect="dark" content="用户评价" :enterable="false" placement="right-start">
       <el-button type="warning" icon="el-icon-star-off" circle></el-button>
    </el-tooltip>
     <el-tooltip class="item" effect="dark" content="删除用户" :enterable="false" placement="right-start">
       <el-button type="danger" icon="el-icon-delete" circle @click="deleteUser(scope.row)"></el-button>
    </el-tooltip>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @prev-click="headlePrev"
      @next-click="headleNext"
      :current-page="page"
      :page-sizes="[3,6,9,12,15,20,30,40,50,100]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
</el-row>
</el-card>
<!-- 添加用户模块 -->
<el-drawer
  title="添加用户"
  :visible.sync="addDrawer"
  :direction="direction1"
  @close="DrawerClosed"
  >
  <!-- :before-close="handleClose" -->

   <!-- 正文区域 -->
<el-form 
:model="user"
 status-icon 
 :rules="rules" 
 ref="ruleForm" 
 label-width="100px" 
 class="demo-ruleForm">
 <el-form-item label="用户名" prop="username">
    <el-input type="text" v-model="user.username" placeholder="用户名必须是3~10位,以字母开头" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input type="password" v-model="user.password" placeholder="密码必须是6~15位,以字母开头" show-password autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="确认密码" prop="checkPassword">
    <el-input type="password" v-model="user.checkPassword" placeholder="密码必须是6~15位,以字母开头" show-password autocomplete="off"></el-input>
  </el-form-item>
   <el-form-item
    prop="email"
    label="邮箱"
    :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
  >
    <el-input v-model="user.email" placeholder="请输入邮箱地址" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="联系电话" prop="mobile">
    <el-input v-model="user.mobile" placeholder="请输入联系电话" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
    <el-button type="success" @click="DrawerClosed()">重置</el-button>
    <el-button @click="addDrawer = false">取 消</el-button>
        
  </el-form-item>
</el-form>
</el-drawer>

<!-- 修改用户模块 -->
<el-drawer
  title="修改用户"
  :visible.sync="editDrawer"
  :direction="direction2"
  @close="DrawerClosed"
  >
  <!-- :before-close="handleClose" -->

   <!-- 正文区域 -->
<el-form 
:model="editUser"
 status-icon 
 :rules="rules" 
 ref="ruleForm" 
 label-width="100px" 
 class="demo-ruleForm">
 <el-form-item label="用户名" prop="username">
    <el-input type="text" v-model="editUser.username" disabled autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="修改密码" prop="password">
    <el-input type="password" v-model="editUser.password" show-password autocomplete="off"></el-input>
  </el-form-item>
  <!-- <el-form-item label="确认密码" prop="checkPassword">
    <el-input type="password" v-model="editUser.checkPassword" show-password autocomplete="off"></el-input>
  </el-form-item> -->
   <el-form-item
    prop="email"
    label="邮箱"
    :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
  >
    <el-input v-model="editUser.email"  autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="联系电话" prop="mobile">
    <el-input v-model="editUser.mobile" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="editUserForm()">确认</el-button>
    <!-- <el-button type="success" @click="DrawerClosed()">重置</el-button> -->
    <el-button @click="editDrawer = false">取 消</el-button>
        
  </el-form-item>
</el-form>
</el-drawer>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      //邮箱验证规则
      let reg = /^\w+@[A-Za-z\d]{2,3}\.[a-zA-Z]{2,3}([a-zA-Z]{2,3})?$/;
     
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 1000);
    };
    //验证手机号的规则
    var validatePhone = (rule, value, callback) => {
       let phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        //密码长度为6~15位
        if (phone.test(value)) {
          callback();
        }else{
           callback(new Error("用户名格式不正确!"));
        }
      }
    };
    //验证用户名的规则
    var validateUser = (rule, value, callback) => {
       let un = /^[A-Za-z]+\w{2,9}$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        //密码长度为6~15位
        if (un.test(value)) {
          callback();
        }else{
           callback(new Error("用户名格式不正确!"));
        }
      }
    };
    //验证密码的规则
    var validatePass = (rule, value, callback) => {
       let un = /^[A-Za-z]+\w{5,14}$/;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        //密码长度为6~15位
        if (un.test(value)) {
          callback();
        }else{
           callback(new Error("密码格式不正确!"));
        }
      }
    };
    //再次输入密码规则
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.user.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      queryTxt: "", // 搜索框
      userList: [],
      page: 1, //当前页数
      limit: 3, //每页显示的条数
      totalCount: 0, //查询的总数
      addDrawer: false, //控制添加窗口的显示和关闭
      editDrawer: false,
      direction1: "rtl", //抽屉的方向 从右往左
      direction2: "ltr", //从左往右
      //存储用户对象
      user: {
        username: "",
        password: "",
        checkPassword: "",
        email: "",
        mobile: "",
      },
      editUser: {
        username: "",
        password: "",
        checkPassword: "",
        email: "",
        mobile: "",
      },
      //定义存储规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator:validateUser, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
           validator: validatePass,
            trigger: "blur",
          },
        ],
        checkPassword: [
          //  { required: true, message: "请输入密码", trigger: "blur" },
          {
            validator: validatePass2,
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          //调用自定义验证规则
          {
            validator: checkEmail,
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //实例被创建时就会被执行
    this.getUserList();
  },
  methods: {
    //获取用户列表
    getUserList() {
      //
      //
      //
      //
      //
      //
      //
      //
      let url = `users?_page=${this.page}&_limit=${this.limit}`;
      //如果搜索框中有值的话,通过输入值进行查询获取新的用户数据
      if (this.queryTxt) {
        url = `users?_page=${this.page}&_limit=${this.limit}&q=${this.queryTxt}`;
      }
      //获取url中的数据
      this.$http.get(url).then((res) => {
        this.userList = res.data;
        //获取数据的总行数
        console.log(res);
        console.log(res.headers["x-total-count"]);
        this.totalCount = parseInt(res.headers["x-total-count"]);
      });
    },
    //监听用户添加和修改的关闭事件方法,重置表单
    DrawerClosed() {
      //使用引用表单名称重置表单
      this.$refs.ruleForm.resetFields();
    },
    //添加用户并提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          console.log("提交失败!!!");
          return false;
        }
        
        this.$http.post("users", this.user).then((res) => {
          if (res.status !== 201) {
            this.$message.error("用户添加失败....");
          } else {
            this.$message.success("用户添加成功....");
          }
          this.addDrawer = false; //控制添加窗口的显示和隐藏
          this.getUserList(); //重新获取用户数据
        });
      });
    },

    //显示修改用户界面
    showEditDrawer(row) {
      console.log(row);
      this.editUser = row;
      this.editDrawer = true; //控制添加窗口的显示和隐藏
    },
    //修改用户
    editUserForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$http
            .put("users/" + this.editUser.id, this.editUser)
            .then((res) => {

              //状态码==200 :
              if (res.status === 200) {
                this.$message.success("用户信息修改成功....");
              } else {
                this.$message.error("用户信息修改失败....");
              }
              this.editDrawer = false; //控制修改窗口的显示和隐藏
              this.getUserList(); //重新获取用户数据
            });
        }
      });
    },

    // //删除用户
    deleteUser(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("users/" + row.id).then((res) => {
            if (res.status !== 200) {
              return this.$message.error("删除失败!");
            }
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //当改变每页显示的条数时执行
    handleSizeChange(val) {
      this.limit = val;
      this.getUserList(); //重新获取用户列表
      this.$notify.info({
        title: "消息",
        message: "改变每页显示的数量",
        position: "top-right",
      });
    },
    //当单击页数的时候执行
    handleCurrentChange(val) {
      this.page = val;
      this.getUserList();
      this.$notify.info({
        title: "消息",
        message: "单击的页数",
        position: "top-right",
      });
    },
    // 单击上一页
    headlePrev(val) {
      this.page = val;
      this.getUserList();
      this.$notify.info({
        title: "消息",
        message: "单击的上一页",
        position: "top-right",
      });
    },
    headleNext(val) {
      this.page = val;
      this.getUserList();
      this.$notify.info({
        title: "消息",
        message: "单击的下一页",
        position: "top-right",
      });
    },
  },
};
</script>
<style lang="less" scoped>
</style>